package com.tianji.learning.utils;

import lombok.Data;

import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
@Data
public class DelayTask<D> implements Delayed {
    //延时任务执行的纳秒值
    private Long deadLineNanos;
    //延时任务的数据
    private D data;

    public DelayTask(Duration duration, D data) {
        //现在时间加延时时间，等于延时任务执行的时间
        this.deadLineNanos = System.nanoTime() + duration.toNanos();
        this.data = data;
    }


    /**
     * 计算延时任务的剩余时间
     *
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(Math.max(deadLineNanos - System.nanoTime(), 0), TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        Long delay = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        if (delay > 0) {
            return 1;
        } else if
        (delay < 0) {
            return -1;
        } else {
            return 0;
        }
    }
}
